package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.config.BasicConfig;
import com.wkbb.basic.feign.WxFeignService;
import com.wkbb.basic.mapper.BlacklistMapper;
import com.wkbb.basic.mapper.UserFaceMapper;
import com.wkbb.basic.mapper.UserInfoMapper;
import com.wkbb.basic.mapper.UserMapper;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.BlackListService;
import com.wkbb.basic.service.UserService;
import com.wkbb.basic.service.WebankService;
import com.wkbb.basic.service.YouTuService;
import com.wkbb.basic.utils.FileUtil;
import com.wkbb.basic.utils.ImageOfbase64UtilDto;
import com.wkbb.basic.utils.WebankUtil;
import com.wkbb.basic.utils.YouTuUtil;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.Constants;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.BlacklistInfoDto;
import com.wkbb.common.dto.basic.RoleTypeDto;
import com.wkbb.common.dto.basic.RoleTypeJsonDto;
import com.wkbb.common.dto.basic.UserFaceDto;
import com.wkbb.common.dto.wx.AccountDto;
import com.wkbb.common.enums.EntranceEnum;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.utils.BeanUtil;
import com.wkbb.common.utils.NewMD5Util;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.UuIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URL;
import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/9
 * @description
 */
@Service
@Slf4j
public class BlacklistServiceImpl extends BaseServiceImpl<Blacklist> implements BlackListService {

    @Autowired
    private BlacklistMapper blacklistMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private YouTuService youTuService;

    @Autowired
    private ServiceConfig serviceConfig;

    @Autowired
    private WxFeignService wxFeignService;

    @Autowired
    private UserFaceMapper userFaceMapper;

    @Autowired
    private BasicConfig basicConfig;

    @Autowired
    private WebankService webankService;

    @Autowired
    private UserService userService;

    @Autowired
    public void setMapper(BlacklistMapper blacklistMapper) {
        super.setMapper(blacklistMapper);
    }

    @Override
    @Transactional
    public ResultDTO<Object> insert(BlacklistInfoDto blacklistInfoDto, String userName) throws Exception {

        //是否在本校已经注册过
        Boolean isRegister = false;
        ResultDTO<AccountDto> accountDtoResultDTO = wxFeignService.getAccountByOrg(blacklistInfoDto.getOrgId());

        if(null!=blacklistInfoDto.getUserId()){

            Map<String, Object> parms = new HashMap<>(2);
            parms.put("userId", blacklistInfoDto.getUserId());
            parms.put("orgId", blacklistInfoDto.getOrgId());
            List<UserFaceDto> userFaceDtos = userFaceMapper.getUserFaceByMapParms(parms);
            //判断这张人脸是否在该校注册过
            if (CollectionUtils.isNotEmpty(userFaceDtos)) {
                Long userId = userFaceDtos.get(0).getUserId();
                isRegister = true;
                //判断是否此人是否已经被设置为黑名单
                Map<String, Object> params = new HashMap<>(2);
                params.put("userId", userId);
                params.put("orgId", blacklistInfoDto.getOrgId());
                Blacklist blacklistReg = blacklistMapper.getByMapParams(params);
                if (blacklistReg == null) {
                    //保存黑名单信息表
                    Blacklist blacklist = new Blacklist();
                    blacklist.setCreatedBy(userName);
                    blacklist.setUpdateBy(userName);
                    blacklistInfoDto.setUserId(userId);
                    BeanUtil.copyProperties(blacklist, blacklistInfoDto);
                    //入库
                    blacklistMapper.insert(blacklist);
                }
            }
        }


        //如果人脸未在该校注册过,则上传优图
        if (!isRegister) {
            //保存USER主表
            User user = new User();
            user.setName(blacklistInfoDto.getName());
            user.setHeadImgUrl(blacklistInfoDto.getHeadImgUrl());
            user.setUserCode(UuIdUtil.getUserCodeByUUId());//生成CODE

            ArrayList<RoleTypeJsonDto> roleTypeJsonsList = new ArrayList<RoleTypeJsonDto>();
            ArrayList<RoleTypeDto> roleTypeList = new ArrayList<RoleTypeDto>();

            RoleTypeDto roleTypeDto = new RoleTypeDto();
            roleTypeDto.setRoleType((short) 6);
            roleTypeDto.setRoleTypeName(RoleTypeEnum.BLACKLIST.getDesc());
            roleTypeList.add(roleTypeDto);

            RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();
            roleTypeJsonDto.setOrgId(blacklistInfoDto.getOrgId());
            roleTypeJsonDto.setRoleTypes(roleTypeList);

            roleTypeJsonsList.add(roleTypeJsonDto);

            user.setRoleType(roleTypeJsonsList);
            user.setStatus(true);

            userMapper.insert(user);

            //保存用户信息表
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getId());
            if (!StringUtils.isEmpty(blacklistInfoDto.getHeadImgUrl())) {
                userInfo.setHeadImgMd5(userService.getImageMD5(blacklistInfoDto.getHeadImgUrl()));
            }
            userInfo.setSex(blacklistInfoDto.getSex());
            userInfoMapper.insert(userInfo);

            //上传微众
            ResultDTO<Object> result = webankService.addWeBankUserFace(blacklistInfoDto.getHeadImgUrl(), user.getUserCode(), blacklistInfoDto.getOrgId(), accountDtoResultDTO.getData().getId(), user.getId(), EntranceEnum.MINI.getValue(), null);

            if (!ResultDTO.checkSuccess(result)) {
                return result;
            }

            //保存黑名单信息表
            Blacklist blacklist = new Blacklist();
            blacklist.setCreatedBy(userName);
            blacklist.setUpdateBy(userName);
            blacklistInfoDto.setUserId(user.getId());
            BeanUtil.copyProperties(blacklist, blacklistInfoDto);
            //入库
            blacklistMapper.insert(blacklist);
            return new ResultDTO<>(blacklistInfoDto);
        }

        return new ResultDTO<>(blacklistInfoDto);
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) throws Exception {
        if (!CollectionUtils.isEmpty(ids)) {
            for (Long id : ids) {
                Blacklist blacklist = blacklistMapper.getByPrimaryKey(id);
                //删除用户
                User user = userMapper.getByPrimaryKey(blacklist.getUserId());
                if (null != user) {
                    user.setStatus(false);
                    userMapper.updateStatus(user);
                }
                //删除用户信息
                Map<String, Object> userInfoParams = new HashMap<>();
                userInfoParams.put("userId", blacklist.getUserId());
                UserInfo userInfo = userInfoMapper.getByMapParams(userInfoParams);
                if (null != userInfo) {
                    userInfoMapper.delete(userInfo);
                }
                //删除个体
                youTuService.deletePerson(blacklist.getOrgId(), userInfo.getUserId());

            }

            //删除黑名单表
            blacklistMapper.deleteBlacklistByIdBatch(ids);
        }
    }

    @Override
    @Transactional
    public ResultDTO<Object> update(BlacklistInfoDto blacklistInfoDto, String userName) throws Exception {

        //先查询历史信息判断是否修改人脸照片
        Boolean isUpdateFace = false;
        Blacklist blacklist1 = blacklistMapper.getByPrimaryKey(blacklistInfoDto.getId());
        if (!blacklistInfoDto.getHeadImgUrl().equals(blacklist1.getHeadImgUrl())) {
            isUpdateFace = true;
        }

        //1,修改用户表
        User user = userMapper.getByPrimaryKey(blacklistInfoDto.getUserId());
        if (isUpdateFace) {
            user.setHeadImgUrl(blacklistInfoDto.getHeadImgUrl());
        }
        user.setName(blacklistInfoDto.getName());
        userMapper.update(user);
        //2,修改用户信息表
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", blacklistInfoDto.getUserId());
        UserInfo userInfo = userInfoMapper.getByMapParams(paramMap);
        if (isUpdateFace) {
            userInfo.setHeadImgMd5(userService.getImageMD5(blacklistInfoDto.getHeadImgUrl()));
        }
        userInfo.setSex(blacklistInfoDto.getSex());
        userInfo.setAge(blacklistInfoDto.getAge());
        userInfoMapper.update(userInfo);

        //3,修改优图人脸（先删除后上传）
        if (isUpdateFace) {
            //删除个体
            ResultDTO<AccountDto> accountDtoResultDTO = wxFeignService.getAccountByOrg(blacklistInfoDto.getOrgId());
            youTuService.deletePerson(blacklistInfoDto.getOrgId(), user.getId());

            //上传优图
            String result = youTuService.addUserFace(new ImageOfbase64UtilDto(blacklistInfoDto.getHeadImgUrl(), FileUtil.encodeImageToBase64(new URL(blacklistInfoDto.getHeadImgUrl()))), user.getUserCode(),
                    blacklistInfoDto.getOrgId(), accountDtoResultDTO.getData().getId(), user.getId());
            if (null != result) {
                if (YouTuUtil.FACENOTCOMPLETE.equals(JSONObject.parseObject(result).get("errorcode"))) {
                    return new ResultDTO<Object>(ErrorCode.FACENOTCOMPLETE);
                } else if (YouTuUtil.PERSONIDNOTEXIST.equals(JSONObject.parseObject(result).get("errorcode"))) {
                    return new ResultDTO<Object>(ErrorCode.PERSONIDNOTEXIST);
                } else if (YouTuUtil.ERRORCODETYPE.equals(JSONObject.parseObject(result).get("errorcode"))) {
                    if (null != JSONObject.parseObject(result).get("result") && serviceConfig.getFaceCompare().compareTo(new BigDecimal(JSONObject.parseObject(result).get("result").toString())) == 1) {
                        return new ResultDTO<Object>(ErrorCode.ACCURACYCOMPARE);
                    }
                    if (null != JSONObject.parseObject(result).get("face_num") && Integer.parseInt(JSONObject.parseObject(result).get("face_num").toString()) == 0) {
                        return new ResultDTO<Object>(ErrorCode.CHECKFACEERROR);
                    }
                } else if (YouTuUtil.ERRORCODETYPE110110.equals(JSONObject.parseObject(result).get("errorcode"))) {
                    return new ResultDTO<Object>(ErrorCode.CHECKFACEERROR);
                }
            }
        }

        //4.修改黑名单
        Blacklist blacklist = new Blacklist();
        blacklist.setUpdateBy(userName);
        BeanUtil.copyProperties(blacklist, blacklistInfoDto);
        blacklistMapper.update(blacklist);
        return new ResultDTO<>(blacklistInfoDto);
    }

    @Override
    public PageInfo<BlacklistInfoDto> getBlacklistInfoList(Map<String, Object> params, Integer pageNo, Integer pageSize)
            throws Exception {

        if (pageNo == null || pageSize == null) {
            return null;
        }

        //分页
        Page<BlacklistInfoDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<BlacklistInfoDto> pageInfo = new PageInfo(this.transforBlacklistDtoList(blacklistMapper.getListByMapParams(params)));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public List<BlacklistInfoDto> getBlackListDtoByMapParams(Map<String, Object> params) {

        return blacklistMapper.getBlackListDtoByMapParams(params);
    }

    /**
     * 组装前端返回数据
     *
     * @param blacklists
     * @return
     * @throws Exception
     */
    private List<BlacklistInfoDto> transforBlacklistDtoList(List<Blacklist> blacklists) throws Exception {

        List<BlacklistInfoDto> blacklistInfoDtos = new ArrayList<>();

        for (Blacklist blacklist : blacklists) {
            BlacklistInfoDto blacklistInfoDto = new BlacklistInfoDto();
            BeanUtil.copyProperties(blacklistInfoDto, blacklist);
            blacklistInfoDtos.add(blacklistInfoDto);
        }
        return blacklistInfoDtos;
    }

    public static void main(String[] args) {

//        String faceIds = "111;222;333;444";
//        List faceIdList = Arrays.asList(faceIds.split(Constants.SEPARATOR_MARK));
//        System.out.println(JSONObject.toJSONString(faceIdList));

        List<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        list.add("333");
        list.add("444");

        StringBuffer sb = new StringBuffer();
        for (String str : list) {
            sb.append(str).append(";");
        }
        System.out.println(sb.toString());
        List faceIdList = Arrays.asList(sb.toString().split(Constants.SEPARATOR_MARK));
        System.out.println(JSONObject.toJSONString(faceIdList));
    }
}